package org.mozhu.learning.algo.binary_search.cases.sqrt;

public class BinarySearchSqrt implements Sqrt {

    @Override
    public double sqrt(double number, double precision) {
        double max = number;
        double min = 0.0;
        while (min <= max) {
            double mid = min + (max - min) / 2;
            System.out.println(mid);
            double square = mid * mid;
            if (abs(square - number) <= precision) {
                return mid;
            }
            if (square > number) {
                max = mid;
            } else if (square < number) {
                min = mid;
            } else {
                return mid;
            }
        }
        return 0;
    }

    private double abs(double v) {
        return v >= 0 ? v : v * -1;
    }
}
